#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import tkinter as tk
from tkinter import ttk
import threading
import json
import time
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from ui.main_window import MainWindow
from core.backup_manager import BackupManager
from config.settings import Settings

class GitBackupTool:
    """Git备份工具主类"""
    
    def __init__(self):
        self.root = tk.Tk()
        self.backup_manager = BackupManager()
        self.settings = Settings()
        
        # 初始化UI
        self.setup_ui()
        
        # 加载配置
        self.load_config()
        
        # 启动定时检查任务
        self.start_scheduler()
    
    def setup_ui(self):
        """设置用户界面"""
        # 设置窗口标题和大小
        self.root.title("Git自动备份工具 v1.0")
        self.root.geometry("1000x700")
        self.root.minsize(800, 600)
        
        # 设置图标
        try:
            icon_path = os.path.join(os.path.dirname(__file__), "assets", "icon.ico")
            if os.path.exists(icon_path):
                self.root.iconbitmap(icon_path)
        except:
            pass
        
        # 创建主窗口
        self.main_window = MainWindow(self.root, self.backup_manager)
        
        # 绑定关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
    
    def load_config(self):
        """加载配置"""
        self.settings.load()
        self.backup_manager.load_tasks()
        
        # 更新UI
        if hasattr(self.main_window, 'load_tasks'):
            self.main_window.load_tasks()
    
    def save_config(self):
        """保存配置"""
        self.settings.save()
        self.backup_manager.save_tasks()
    
    def start_scheduler(self):
        """启动定时检查任务"""
        def check_scheduled_tasks():
            while True:
                try:
                    # 检查是否有需要执行的计划任务
                    self.backup_manager.check_scheduled_tasks()
                    
                    # 每分钟检查一次
                    time.sleep(60)
                except Exception as e:
                    print(f"检查计划任务时出错: {e}")
                    time.sleep(60)
        
        # 在后台线程中运行
        scheduler_thread = threading.Thread(target=check_scheduled_tasks, daemon=True)
        scheduler_thread.start()
    
    def on_closing(self):
        """窗口关闭事件"""
        # 保存配置
        self.save_config()
        
        # 关闭窗口
        self.root.destroy()
    
    def run(self):
        """运行应用"""
        self.root.mainloop()

if __name__ == "__main__":
    app = GitBackupTool()
    app.run()